import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue')
    },
    {
      path: '/login',
      name: 'login',
      component:LoginView
    },
    {
      path: '/register',
      name: 'register',
      component:RegisterView
    }
  ]
})

router.beforeEach((to, from, next) => {
  // 判断用户是否已经完成登录，可以是一个变量或者一个方法
  const isAuthenticated = () => {
    const token = localStorage.getItem('token') // 假设 token 是保存在 localStorage 中的
    return !!token // 如果 token 存在，则说明用户已经完成登录
  }

  // 如果用户没有完成登录且要访问需要登录的页面，则跳转到登录页面
  if (!isAuthenticated() && to.path==='/') {
    alert('请您先登录！')
    next({ path: '/login' })
  }
  if (!isAuthenticated() && to.path==='/about') {
    alert('请您先登录！')
    next({ path: '/login' })
  } 
  else {
    next()
  }
})

export default router
